package com.easyjob.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easyjob.entity.enums.PageSize;
import com.easyjob.entity.po.*;
import com.easyjob.entity.query.*;
import com.easyjob.entity.vo.PaginationResultVO;
import com.easyjob.exception.BusinessException;
import com.easyjob.mappers.*;
import com.easyjob.mappers.plus.BankMapper;
import com.easyjob.mappers.plus.CategoryPlusMapper;
import com.easyjob.mappers.plus.ChapterPlusMapper;
import com.easyjob.mappers.plus.QuestionPlusMapper;
import com.easyjob.service.ChapterService;
import com.easyjob.utils.StringTools;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Const
 * @version 1.0
 * @email 1357042069@qq.com
 * @date 2023/12/14
 */
@Service("chapterBankService")
public class ChapterServiceImpl implements ChapterService {
    @Resource
    private QuestionBankMapper<QuestionBank, QuestionBankQuery> questionBankMapper;


    @Resource
    private ChapterMapper<Chapter, ChapterQuery> chapterMapper;

    @Resource
    private CategoryPlusMapper categoryPlusMapper;

    @Resource
    private ChapterPlusMapper chapterPlusMapper;

    @Resource
    private BankMapper bankMapper;

    @Resource
    private QuestionPlusMapper questionPlusMapper;


    @Override
    public Integer updateChapterByChapterId(Chapter bean, Integer chapterId) {
        return this.chapterMapper.updateByChapterId(bean, chapterId);
    }


    @Override
    public Integer deleteChapterByChapterId(Integer chapterId) {
        Long count = questionPlusMapper.selectCount(new QueryWrapper<ExamQuestion>().eq("chapter_id", chapterId));
        if (count > 0) {
            throw new BusinessException("该章节下已有题目！");
        }
        return chapterPlusMapper.delete(new QueryWrapper<Chapter>().eq("chapter_id", chapterId));
    }

    @Override
    public List<Chapter> loadAllChapterByType(Integer categoryId) {
        if (categoryId == null) return chapterPlusMapper.selectList(null);
        return chapterPlusMapper.selectList(new QueryWrapper<Chapter>().eq("category_id", categoryId));
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public List<Chapter> findListByParam(ChapterQuery param) {
        return this.chapterMapper.selectList(param);
    }



    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(ChapterQuery param) {
        return this.chapterMapper.selectCount(param);
    }

    @Override
    public int findCount(ChapterQuery param) {
        Integer bankId = param.getBankId();
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        if (param.getBankId() != null) {
            queryWrapper.eq("bank_id", bankId);
        }
        List<Integer> categoryList = categoryPlusMapper.
                selectList(queryWrapper)
                .stream()
                .map(Category::getCategoryId)
                .collect(Collectors.toList());
        QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<Chapter>().in("category_id", categoryList);
        if (param.getCategoryId() != null) chapterQueryWrapper.eq("category_id", param.getCategoryId());
        if (param.getChapterName() != null) chapterQueryWrapper.like("chapter_name", param.getChapterName());
        int value = chapterPlusMapper.selectCount(chapterQueryWrapper).intValue();
        return value;
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResultVO<Chapter> findListByPage(ChapterQuery param) {
        int count = this.findCount(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();
        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);
        List<Chapter> list = this.findList(param);
        PaginationResultVO<Chapter> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
        return result;
    }

    @Override
    public List findList(ChapterQuery param) {
        Integer bankId = param.getBankId();
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        if (param.getBankId() != null) {
            queryWrapper.eq("bank_id", bankId);
        }
        List<Integer> categoryList = categoryPlusMapper.selectList(queryWrapper)
                .stream()
                .map(Category::getCategoryId)
                .collect(Collectors.toList());
        SimplePage simplePage = param.getSimplePage();
        Page p = new Page(simplePage.getPageNo(),
                simplePage.getPageSize(),
                simplePage.getCountTotal());
        QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<Chapter>().in("category_id", categoryList);
        if (param.getCategoryId() != null) chapterQueryWrapper.eq("category_id", param.getCategoryId());
        if (param.getChapterName() != null) chapterQueryWrapper.like("chapter_name", param.getChapterName());
        chapterQueryWrapper.orderByAsc("sort");
        chapterPlusMapper.selectPage(p, chapterQueryWrapper);
        List<Chapter> records = p.getRecords();
        records.forEach(record -> {
            Integer categoryId = record.getCategoryId();
            Category category = categoryPlusMapper.selectOne(new QueryWrapper<Category>().eq("category_id", categoryId));
            Integer tBankId = category.getBankId();
            String bankName = bankMapper.selectOne(new QueryWrapper<QuestionBank>().eq("bank_id", tBankId)).getBankName();
            record.setCategoryName(category.getCategoryName());
            record.setBankId(tBankId);
            record.setBankName(bankName);
        });
        return records;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(Chapter bean) {
        return this.chapterMapper.insert(bean);
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<Chapter> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.chapterMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<Chapter> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.chapterMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 多条件更新
     */
    @Override
    public Integer updateByParam(Chapter bean, ChapterQuery param) {
        StringTools.checkParam(param);
        return this.chapterMapper.updateByParam(bean, param);
    }

    /**
     * 多条件删除
     */
    @Override
    public Integer deleteByParam(ChapterQuery param) {
        StringTools.checkParam(param);
        return this.chapterMapper.deleteByParam(param);
    }


    @Override
    public Chapter getChapterByChapterId(Integer chapterId) {
        return this.chapterMapper.selectByChapterId(chapterId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveChapter(Chapter chapter) {
        if (null == chapter.getChapterId()) {
            ChapterQuery chapterQuery = new ChapterQuery();
            Integer count = Math.toIntExact(chapterPlusMapper.selectCount(null));
            chapterQuery.setSort(count + 1);
            chapterPlusMapper.insert(chapter);
        } else {
            chapterPlusMapper.update(chapter, new UpdateWrapper<Chapter>().eq("chapter_id", chapter.getChapterId()));
//            chapterPlusMapper.updateById(chapter);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeSort(String chapterIds) {
        String[] chapterIdArray = chapterIds.split(",");
        Integer index = 1;
        for (String chapterIdStr : chapterIdArray) {
            Integer chapterId = Integer.parseInt(chapterIdStr);
            Chapter chapter = new Chapter();
            chapter.setSort(index);
            chapterPlusMapper.update(chapter, new UpdateWrapper<Chapter>().eq("chapter_id", chapterId));
//            chapterMapper.updateByChapterId(chapter, chapterId);
            index++;
        }
    }
}
